<template>
  <div class="activity-detail" v-infinite-scroll="loadMore" :infinite-scroll-immediate="false">
    <!-- 背景图区域 -->
    <div class="background-image-container">
      <!-- 返回按钮 -->
      <button class="back-button" @click="handleBack">
        <svg
          width="32"
          height="32"
          viewBox="0 0 32 32"
          fill="none"
          xmlns="http://www.w3.org/2000/svg">
          <path
            d="M11.2935 8.89258C11.684 8.50247 12.3171 8.50224 12.7075 8.89258C13.0977 9.28299 13.0976 9.91615 12.7075 10.3066L8.01318 15H20.5034L20.605 15.0049C21.1094 15.0559 21.5034 15.4821 21.5034 16C21.5033 16.5178 21.1093 16.9441 20.605 16.9951L20.5034 17H8.01514L12.7075 21.6924C13.0978 22.0828 13.0975 22.7159 12.7075 23.1064C12.317 23.4969 11.684 23.4969 11.2935 23.1064L4.89307 16.707C4.50266 16.3166 4.50276 15.6835 4.89307 15.293L11.2935 8.89258ZM25.6001 8.59961C26.1523 8.59961 26.6 9.0474 26.6001 9.59961V22.3994C26.6001 22.9517 26.1524 23.3994 25.6001 23.3994C25.0479 23.3994 24.6001 22.9517 24.6001 22.3994V9.59961C24.6002 9.04744 25.0479 8.59967 25.6001 8.59961Z"
            fill="#222222" />
        </svg>
      </button>

      <!-- 背景图 - 增加过渡色和加载状态 -->
      <div class="image-wrapper">
        <!-- 背景色占位符 -->
        <div class="image-placeholder" :class="{ loaded: isImageLoaded }"></div>
        <!-- 图片本身 -->
        <img
          :src="activityDetail.back_img"
          class="background-image"
          alt=""
          @load="handleImageLoad"
          :class="{ loaded: isImageLoaded }" />
      </div>

      <!-- 背景图中的Join按钮 -->
      <div class="background-join-button">
        <button class="join-btn" @click="handleJoinActivity">Join Contest</button>
      </div>
    </div>

    <!-- Tab切换 -->
    <div
      class="tab-container sticky top-0 z-10 transition-all duration-300"
      :class="{ 'bg-[#fff]': isSticky }"
      ref="stickyRef">
      <div class="tabs flex justify-center gap-[40px]">
        <div
          :class="activeTab === 'info' ? 'base_active_tab_item' : 'base_tab_item'"
          @click="switchTab('info')">
          Info & Awards
        </div>
        <div
          :class="activeTab === 'gallery' ? 'base_active_tab_item' : 'base_tab_item'"
          @click="switchTab('gallery')">
          Gallery
        </div>
        <!-- 添加Winners标签 -->
        <div
          :class="activeTab === 'winners' ? 'base_active_tab_item' : 'base_tab_item'"
          @click="switchTab('winners')">
          Winners
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-container">
      <!-- Info & Awards Tab -->
      <div v-show="activeTab === 'info'" class="info-tab">
        <h1>
          {{ activityDetail.title }}
        </h1>

        <!-- 活动描述 -->
        <RichTextRenderer :content="activityDetail.info" class="description-html block-theme" />
      </div>

      <!-- Gallery Tab -->
      <div v-show="activeTab === 'gallery'" class="gallery-tab">
        <Product
          :products="galleryData"
          :loadMoreLoading="loading"
          :hasMore="hasMore"
          :loading="false" />
      </div>

      <!-- Winners Tab -->
      <div v-show="activeTab === 'winners'" class="winners-tab">
        <Winners :products="winnersData" />
      </div>
    </div>
  </div>
  <VoteDialog v-if="dialogStore.showVoteDialog" />
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ActivityAPI } from '@/api/activity';
  import { ActivityVO, FeedVO } from '@/types/activity';
  import Product from './product.vue';
  import { useSticky } from '@/hook/useSticky';
  import Winners from './winners.vue';
  import VoteDialog from './VoteDialog.vue';
  import { useDialogStore } from '@/store/dialog';
  import RichTextRenderer from '@/components/RichTextRenderer.vue';
  import { FeedItem } from '@/api/feeds';

  const route = useRoute();
  const router = useRouter();
  const dialogStore = useDialogStore();

  const stickyRef = ref<any>(null);
  const isSticky = useSticky(stickyRef);

  // 活动详情数据
  const activityDetail = ref<ActivityVO>({
    aid: '',
    title: '',
    img: '',
    back_img: '',
    info: '',
    participant_count: 0,
    participant_feed_count: 0,
    status: 0,
    start_time: '',
    end_time: '',
  });

  // 画廊数据
  const galleryData = ref<FeedItem[]>([]);
  // 获奖者数据
  const winnersData = ref<FeedItem[]>([]);
  // 加载状态
  const loading = ref(false);
  // 是否还有更多数据
  const hasMore = ref(true);
  // 当前页
  const currentPage = ref(0);
  // 每页条数
  const pageSize = ref(10);

  // 当前激活的Tab
  const activeTab = ref('gallery');

  // 获取活动详情
  const getActivityDetail = async () => {
    const aid = route.query.aid as string;
    if (!aid) {
      console.error('Activity ID is required');
      return;
    }
    const res = await ActivityAPI.getActivityDetail({
      aid,
    });
    activityDetail.value = res.data;
  };

  // 获取活动作品列表
  const getActivityFeeds = async (loadMore: boolean = false) => {
    if (loading.value || !hasMore.value) return;

    loading.value = true;
    const aid = route.query.aid as string;
    if (!loadMore) {
      currentPage.value = 0;
    }

    try {
      const res = await ActivityAPI.getActivityFeeds({
        aid: aid,
        start: currentPage.value,
        size: pageSize.value,
      });

      const newData = res.data.feeds || [];

      // 如果是第一页，替换数据；否则追加数据
      if (!loadMore) {
        galleryData.value = newData;
      } else {
        galleryData.value.push(...newData);
      }

      // 判断是否还有更多数据
      hasMore.value = res.data.has_more;

      // 增加页码
      currentPage.value++;
    } catch (error) {
      console.error('获取活动列表失败:', error);
      // 可以在这里添加错误提示
    } finally {
      loading.value = false;
    }
  };

  // 获取活动详情
  const getActivityWinners = async () => {
    const aid = route.query.aid as string;
    if (!aid) {
      console.error('Activity ID is required');
      return;
    }
    try {
      const res = await ActivityAPI.getActivityWinners({
        aid,
      });
      winnersData.value = res.data;
    } catch (error) {
      console.error('获取活动获奖者失败:', error);
      // 可以在这里添加错误提示
    }
  };

  // 切换Tab
  const switchTab = async (tab: string) => {
    activeTab.value = tab;
  };

  // 处理加入活动
  const handleJoinActivity = () => {
    if (!route.query.aid) {
      console.error('Activity ID is required');
      return;
    }
    router.push({
      path: '/generator/txt2img',
      query: {
        aid: route.query.aid,
      },
    });
  };

  // 处理返回上一页
  const handleBack = () => {
    router.back();
  };

  // 组件挂载时获取活动详情
  onMounted(() => {
    getActivityDetail();
    getActivityFeeds(false);
    getActivityWinners();
  });

  // 加载更多
  const loadMore = async () => {
    getActivityFeeds(true);
  };

  // 新增：图片加载状态
  const isImageLoaded = ref(false);

  // 新增：处理图片加载完成
  const handleImageLoad = () => {
    isImageLoaded.value = true;
  };
</script>

<style scoped lang="scss">
  @use '@/styles/mixins.scss' as *;
  .activity-detail {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    position: relative;
  }

  .background-image-container {
    width: 100%;
    height: px-to-vw(600);
    overflow: hidden;
    position: relative;
    z-index: 1;
  }

  // 新增：图片包装器
  .image-wrapper {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }

  // 新增：图片占位符（过渡色）
  .image-placeholder {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #f5f5f5; // 浅灰色作为过渡背景色
    // 使用渐变色彩增强视觉效果
    background: linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%);
    transition: opacity 0.3s ease-in-out;
    z-index: 1;
  }

  // 新增：图片加载完成后隐藏占位符
  .image-placeholder.loaded {
    opacity: 0;
    display: none;
  }

  .background-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
    position: relative;
    z-index: 2;
    opacity: 0; // 初始透明度为0
    transition: opacity 0.3s ease-in-out; // 添加过渡效果
  }

  // 新增：图片加载完成后显示
  .background-image.loaded {
    opacity: 1;
  }

  .background-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
  }

  // 返回按钮样式
  .back-button {
    position: absolute;
    top: 24px;
    left: 24px;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 3;
    &:hover {
      border-radius: 8px;
      background: #ededed;
    }
  }

  // 背景图中的Join按钮
  .background-join-button {
    position: absolute;
    bottom: 40px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 3;
    // width:
    width: 348px;

    .join-btn {
      width: 100%;
      height: 64px;
      background: linear-gradient(90deg, #f76b1b 0%, #dc3a0e 100%);
      border: none;
      border-radius: 8px;
      color: white;
      font-size: 24px;
      font-weight: 700;
      cursor: pointer;
      transition: all 0.3s ease;
    }

    .join-btn:hover:not(.disabled) {
      background: linear-gradient(90deg, #f78647 0%, #e1603d 100%);
    }

    .join-btn.disabled {
      background: #e5e5e5;
      color: #7a7a7a;
    }
  }

  .tab-container {
  }

  .tabs {
    margin: 8px auto;
  }

  .tab-item {
    padding: 11px 20px;
    cursor: pointer;
    font-weight: 500;
    color: #7a7a7a;
    position: relative;

    &.active {
      color: #f76b1b;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: auto;
        min-width: 50%;
        max-width: 80%;
        height: 2px;
        background: #f76b1b;
        border-radius: 3px;
      }
    }
  }
  .content-container {
    padding-bottom: 80px;
  }
  .info-tab {
    padding-top: 24px;
    h1 {
      font-size: 94px;
      font-weight: 600;
      color: #222222;
      margin-bottom: 40px;
      text-align: center;
      padding: 0 120px;
      word-wrap: break-word;
    }
  }

  .description-html {
    padding: 0 240px;
    color: #222222;
  }
</style>
